package com.atguigu.flink.chapter05.sink;

import com.atguigu.flink.bean.WaterSensor;
import com.alibaba.fastjson.JSON;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.ArrayList;

public class Flink03_Sink_ES_Unbounded {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStream<WaterSensor> s1 = env
                .socketTextStream("hadoop162", 9999)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                });

        ArrayList<HttpHost> hosts = new ArrayList<>();
        hosts.add(new HttpHost("hadoop162",9200));
        hosts.add(new HttpHost("hadoop163",9200));
        hosts.add(new HttpHost("hadoop164",9200));

        ElasticsearchSink.Builder<WaterSensor> esBuilder = new ElasticsearchSink.Builder<>(hosts, new ElasticsearchSinkFunction<WaterSensor>() {
            @Override
            public void process(WaterSensor element, RuntimeContext ctx, RequestIndexer indexer) {

                IndexRequest index = Requests
                        .indexRequest()
                        .index("sensor")
                        .type("_doc")
                        .id(element.getId())
                        .source(JSON.toJSONString(element), XContentType.JSON);

                indexer.add(index);

            }
        });

        esBuilder.setBulkFlushInterval(1000);
        esBuilder.setBulkFlushMaxActions(3);
        esBuilder.setBulkFlushMaxSizeMb(30);

        s1.addSink(esBuilder.build());

        env.execute();

    }
}
